public class Offer_29 {

    /**
     * 剑指 Offer 29. 顺时针打印矩阵
     * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字。
     * <p>
     * 示例 1：
     * <p>
     * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
     * 输出：[1,2,3,6,9,8,7,4,5]
     * 示例 2：
     * <p>
     * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
     * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
     */

    public static int[] spiralOrder(int[][] matrix) {
        int row = matrix.length;
        if (row == 0) {
            return matrix[0];
        }
        int column = matrix[0].length;
        int[] resultArray = new int[row * column];
        int top = 0;
        int bottom = row - 1;
        int left = 0;
        int right = column - 1;
        int index = 0;
        while (true) {
            for (int i = left; i <= right; i++) {
                resultArray[index++] = matrix[top][i];
            }
            if (top++ > bottom) break;

            for (int i = top; i <= bottom; i++) {
                resultArray[index++] = matrix[i][right];
            }
            if (right-- < left) break;

            for (int i = right; i >= left; i--) {
                resultArray[index++] = matrix[bottom][i];
            }
            if (bottom-- < top) break;

            for (int i = bottom; i >= top; i--) {
                resultArray[index++] = matrix[i][left];
            }
            if (left++ > right) break;
        }
        return resultArray;
    }


    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        System.out.println(matrix);
        int[] result = spiralOrder(matrix);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }
        System.out.println();
    }
}
